<template>
  <div class="container">
    <div class="app-container">
      <div class="role-operate">
        <el-button type="primary" size="mini" @click="showDialog = true">添加角色</el-button>
        <!-- 列表 -->
        <el-table :data="list">
          <el-table-column prop="name" align="center" label="角色" width="200">
            <template #default="{ row }">
              <el-input v-if="row.isEdit" v-model="row.editRow.name" size="mini" />
              <span v-else>{{ row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="state" align="center" label="启用" width="200">
            <template #default="{row}">
              <el-switch
                v-if="row.isEdit"
                v-model="row.editRow.state"
                :active-value="1"
                :inactive-value="0"
                size="mini"
              />
              <span v-else>
                {{ row.state === 1 ? '已启用' : '已禁用' }}
              </span>

            </template>

          </el-table-column>
          <el-table-column prop="description" align="center" label="描述">
            <template #default="{ row }">
              <el-input v-if="row.isEdit" v-model="row.editRow.description" type="textarea" size="mini" />
              <span v-else>{{ row.description }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作">
            <template #default="{ row }">
              <template v-if="row.isEdit">
                <!-- 编辑状态 -->
                <el-button type="primary" size="mini" @click="btnConfirm(row)">确定</el-button>
                <el-button size="mini" @click="row.isEdit = false">取消</el-button>
              </template>
              <template v-else>
                <!-- 非编辑状态 -->
                <el-button size="mini" type="text" @click="btnPermission(row.id)">分配权限</el-button>
                <el-button size="mini" type="text" @click="handleEdit(row)">编辑</el-button>
                <!-- <el-button size="mini" type="text">删除</el-button> -->
                <template>
                  <el-popconfirm title="这是一段内容确定删除吗？" @onConfirm="confirmDel(row.id)">
                    <el-button slot="reference" style="margin-left: 10px;" type="text">删除</el-button>
                  </el-popconfirm>
                </template>
              </template>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row type="flex" style="height: 60px;" justify="end" align="middle">
          <el-pagination
            small
            layout="prev, pager, next"
            :total="total"
            @current-change="handleCurrentChange"
          />
        </el-row>
        <!-- 新增模态框 -->
        <el-dialog title="新增角色" :visible.sync="showDialog" width="35%" @close="btnCancel">
          <el-form ref="addForm" :rules="rules" :model="addForm" label-width="120px">
            <el-form-item label="角色名称" prop="name">
              <el-input v-model="addForm.name" style="width: 300px;" size="mini" />
            </el-form-item>
            <el-form-item label="启用" prop="state">
              <el-switch
                v-model="addForm.state"
                active-color="#13ce66"
                :active-value="1"
                :inactive-value="0"
                inactive-color="#ff4949"
                size="mini"
              />
            </el-form-item>
            <el-form-item label="角色描述" prop="description">
              <el-input v-model="addForm.description" type="textarea" style="width: 300px;" />
            </el-form-item>
            <el-form-item>

              <el-button type="primary" size="mini" @click="addRole">确定</el-button>
              <el-button size="mini" @click="btnCancel">取消</el-button>

            </el-form-item>
          </el-form>
        </el-dialog>
        <!-- 弹层 -->
        <!-- 放置权限弹层 -->
        <el-dialog :visible.sync="showPermissionDialog" title="分配权限">
          <!-- 分配权限-->
          <!-- check-strictly 在显示复选框的情况下，是否严格的遵循父子不互相关联的做法，默认为 false -->
          <el-tree
            ref="permTree"
            check-strictly
            :data="permissionList"
            :props="{ label: 'name' }"
            node-key="id"
            :default-checked-keys="permIds"
            show-checkbox
            default-expand-all
          />
          <el-row slot="footer" type="flex" justify="center">
            <el-col :span="6">
              <el-button size="small" type="primary" @click="btnPermissionOk">确定</el-button>
              <el-button size="small" @click="showPermissionDialog = false">取消</el-button>
            </el-col>
          </el-row>
        </el-dialog>
      </div>
    </div>
  </div>
</template>
<script>
import { transListToTresData } from '@/utils'
import { getPermissionList } from '@/api/permission'
import { getRoleList, addRole, updateRole, delRole, getRoleDetail, assignPrem } from '@/api/role'
export default {
  name: 'Role',
  data() {
    return {
      list: [],
      total: 0, // 总条数
      // 分页
      params: {
        page: 1, // 当前页码
        pagesize: 40 // 当前页码条数
      },

      showDialog: false, // 模态框开关
      value: true, // 开关
      // 新增
      addForm: {
        name: '', // 角色名称
        description: '', // 角色描述
        state: 0 // 角色状态

      },
      rules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' },
          { min: 2, max: 10, message: '角色名称的长度为2-10个字符', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '角色描述不能为空', trigger: 'blur' },
          { min: 2, max: 10, message: '角色描述长度为2-10个字符', trigger: 'blur' }
        ]
      },
      showPermissionDialog: false, // 分配权限弹层
      permissionList: [], // 权限列表
      currentRoleid: null, // 当前角色id
      permIds: [] // 角色的权限集合

    }
  },
  created() {
    this.getRoleList() // 渲染
  },

  methods: {
    // 分配权限
    async  btnPermission(id) {
      // 获取权限数据
      this.permissionList = transListToTresData(await getPermissionList(), 0)
      this.currentRoleid = id // 记录id
      // 获取详情
      const { permIds } = await getRoleDetail(id)
      // 赋值数据
      this.permIds = permIds
      // 显示弹层
      this.showPermissionDialog = true
    },

    async btnPermissionOk() {
      // getCheckedKeys:若节点可被选择（即 show-checkbox 为 true），则返回目前被选中的节点的 key 所组成的数组
      console.log(this.$refs.permTree.getCheckedKeys())
      await assignPrem({
        id: this.currentRoleid,
        permIds: this.$refs.permTree.getCheckedKeys()
      })
      this.$message.success('分配权限成功')
      this.showPermissionDialog = false
    },

    async getRoleList() {
      const { rows, total } = await getRoleList(this.params)
      // console.log(result)
      this.list = rows
      this.total = total
      this.list.forEach(item => {
        // 缓存数据
        this.$set(item, 'editRow', {
          name: item.name,
          description: item.description,
          state: item.state

        })
        // item.isEdit = false
        this.$set(item, 'isEdit', false)
      })
    },

    // 确定编辑
    async btnConfirm(row) {
      // 1.非空校验
      // 2.调用更新接口
      // 3.提示用户
      // 4.更新显示数据
      // 退出编辑状态

      if (row.editRow.name && row.editRow.description) {
        await updateRole({ ...row.editRow, id: row.id })
        this.$message.success('更新角色成功')
        // eslint-disable-next-line require-atomic-updates
        // row.name = row.editRow.name
        // // eslint-disable-next-line require-atomic-updates
        // row.state = row.editRow.state/
        Object.assign(row, {
          ...row.editRow,
          isEdit: false
        })
      } else {
        this.$message.warning('名称和描述不能为空')
      }
    },

    // 编辑行内状态
    handleEdit(row) {
      row.editRow.name = row.name
      row.editRow.description = row.description
      row.editRow.state = row.state
      row.isEdit = true
    },

    // 删除
    async confirmDel(id) {
      await delRole(id)
      if (this.list.length === 1) {
        this.params.page--
        this.getRoleList()
      }
    },

    // 切换分页时 请求新的数据
    handleCurrentChange(val) {
      this.params.pagesize = val // 赋值当前页码
      console.log(`当前页: ${val}`)
      this.getRoleList()
    },

    // 确认按钮
    addRole() {
      this.$refs.addForm.validate(async valid => {
        if (!valid) return
        const res = await addRole(this.addForm)
        console.log(res)
        // 提示用户
        this.$message.success('新增角色成功')
        this.params.page = 1
        this.getRoleList() // 渲染
        this.btnCancel() // 重置
      })
    },

    // 取消按钮
    btnCancel() {
      this.$refs.addForm.resetFields()
      this.showDialog = false
    }
  }

}
</script>

<style lang="scss" scoped>
.role-operate {
  padding: 20px;
}
</style>
